
/**
 * 向后端请求用户有权限的项目列表
 */
 import storage from 'store'
 import { getIdentities } from '@/api/login'
 const auth = {
   state: {
     client_Id: storage.get('client_Id'),
     tenant_Id: storage.get('tenant_Id'),
     app_Id: storage.get('app_Id'),
     tenant_List: [],
     portalType: 'default',
     microPermissions: [], // 子应用 操作权限
     auth_pattern: +process.env.VUE_APP_AUTH_PATTERN, // 授权模式
     identityList: []// 身份列表（切换组织机构身份）
   },

   mutations: {
     SET_CLIENT_ID: (state, clientId) => {
       state.client_Id = clientId
       storage.set('client_Id', clientId)
     },
     SET_TENANT_ID: (state, tenantId) => {
      state.tenant_Id = tenantId
      storage.set('tenant_Id', tenantId)
    },
     SET_TENANT_LIST: (state, tenantList) => {
       state.tenant_List = tenantList
       storage.set('tenant_List', tenantList)
     },
     SET_APP_ID: (state, id) => {
      state.app_Id = id
      storage.set('app_Id', id)
      },
     SET_portalType: (state, portalType) => {
       state.portalType = portalType
       storage.set('portalType', portalType)
     },
     SET_Micro_Permissions: (state, list) => {
       state.microPermissions = list
     },
     SET_Auth_Pattern: (state, pattern) => {
       state.auth_pattern = pattern
       storage.set('auth_pattern', pattern)
     },
     SET_ORGLIST: (state, list) => {
       state.identityList = list
     },
     SET_ORGINFO: (state, data) => {
       window.localStorage.setItem('organId', data.organId) // 当前机构Id,初始化时默认值
       window.localStorage.setItem('organName', data.organName) // 当前机构名称
       window.localStorage.setItem('fullIdPath', data.fullIdPath) // 当前机构全路径
       window.localStorage.setItem('orgForm', data.orgForm) // 机构类型
       window.localStorage.setItem('fullName', data.fullName) // 机构全名
       // window.localStorage.setItem('versionCode', data.version.versionCode) // 当前项目版本
     }
   },

   actions: {

     // 当前登录人的组织机构分类
     GetIdentities ({ state, commit }, key) {
       return new Promise((resolve, reject) => {
         getIdentities().then((res) => {
          if (res && res.length) {
            commit('SET_ORGLIST', res)
            console.log(window.localStorage.getItem('organId'))
            const currentOrganId = window.localStorage.getItem('organId')
            if (currentOrganId) {
              const data = res.find((e) => e.organId === currentOrganId)
              commit('SET_ORGINFO', data || res[0])
            } else {
              commit('SET_ORGINFO', res[0])
            }
            resolve(true)
          } else {
           commit('SET_ORGINFO', {})
           resolve(false)
          }
         }).catch((err) => {
           reject(err)
         })
       })
     },
     SetCurrentOrgan ({ state, commit }, data) {
       return new Promise((resolve, reject) => {
         commit('SET_ORGINFO', data)
         resolve()
       })
     }

   }
 }

 export default auth
